package ut.servlet;
import ut.data.User;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
public class Join extends HttpServlet{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		// 檢查驗證碼
		HttpSession session = request.getSession();
		if(session.getAttribute("code") == null || request.getParameter("code") == null){
			return;
		}else if(!session.getAttribute("code").toString().equals(request.getParameter("code"))){
			response.setIntHeader("result", 2); // 驗證碼錯誤
			return;
		}
		// 取得並驗證使用者輸入資訊
		String email, password, name;
		if(request.getParameter("email") == null || request.getParameter("password") == null || request.getParameter("name") == null){
			return;
		}else{
			email = request.getParameter("email");
			if(!email.matches(".+@.+")){
				return;
			}
			password = request.getParameter("password");
			if(!password.matches("[a-zA-Z0-9~!@*]{4,16}")){
				return;
			}
			name = request.getParameter("name");
		}
		// 將新的使用者加入資料庫
		int result = User.join(email, password, name); // -1: 系統錯誤、0: 帳號重複、1: 成功、2: 驗證碼錯誤
		if(result == 1){
			// 刪除內部儲存的驗證碼
			session.removeAttribute("code");
		}
		response.setIntHeader("result", result);
	}
}